import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:lcapp/api/request/api_client.dart';
import 'package:lcapp/data/app_update_data_entity.dart';
import 'package:lcapp/model/permission/permission_operate.dart';
import 'package:lcapp/tools/file_tool.dart';
import 'package:open_file/open_file.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:url_launcher/url_launcher_string.dart';
import 'package:uuid/uuid.dart';

class AppUpdatePage extends StatefulWidget {
  final AppUpdateDataEntity entity;
  const AppUpdatePage({Key? key, required this.entity}) : super(key: key);

  @override
  State<AppUpdatePage> createState() => _AppUpdatePageState();
}

class _AppUpdatePageState extends State<AppUpdatePage> {

  String btnTitle='更新';
  late String filePath;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Center(
        child: Container(
          width: 650.w,
          padding: EdgeInsets.symmetric(horizontal: 40.w,vertical: 30.w),
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10.w)
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(widget.entity.title??'发现新版本',style: TextStyle(
                  color: Colors.black,
                  fontSize: 40.sp,
                  fontWeight: FontWeight.w500
              ),),
              SizedBox(height: 10.w,),
              Text(widget.entity.version??'',style: TextStyle(
                  color: Color(0xff1A051D),
                  fontSize: 28.sp,
                  fontWeight: FontWeight.w500
              ),),
              SizedBox(height: 40.w,),
              Text(widget.entity.detail??'1、优化已知功能\n2、提升用户体验',style: TextStyle(
                  color: Colors.black,
                  fontSize: 30.sp,
                  fontWeight: FontWeight.w500
              ),),
              SizedBox(height: 80.w,),
              GestureDetector(
                onTap: ()async{
                  if(Platform.isIOS){
                    if(await canLaunchUrlString(widget.entity.iosUrl!)){
                      launchUrl(Uri.parse(widget.entity.iosUrl!),mode: LaunchMode.externalApplication);
                    }
                  }else{
                    if(btnTitle=='更新'){
                      btnTitle = '正在下载';
                      download();
                    }else  if(btnTitle=='安装新版本'){
                      inspectPermission(context,content:"获取本地存储文件权限。“粮策”申请获取本地存储文件权限，用于APP更新。",permissionList:[permissionType.storage],permissionCallBack: (){
                        // 安装APK
                        OpenFile.open(filePath);
                      },);
                    }
                  }
                },
                child: Container(
                  width: 540.w,
                  height: 100.w,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(10.w),
                      color: Color(0xffFA6E28)
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Text(btnTitle,style: TextStyle(
                          color: Colors.white,
                          fontSize: 36.sp,
                          fontWeight: FontWeight.w400
                      ))
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  download()async{
    String dirPath = await FileTool.getStorageDir(relativePath: "apk/");
    filePath = dirPath+Uuid().v4()+'.apk';
    Dio _dio = Dio();
    _dio.options.connectTimeout = Duration(minutes: 10);
    _dio.options.receiveTimeout =Duration(minutes: 10);
    _dio.download(widget.entity.androidUrl!, filePath,onReceiveProgress: (received, total){
      print('下载====$received == $total');
      if (total != -1) {
        if(mounted){
          setState(() {
            btnTitle = '正在下载 ${(received / total * 100).toStringAsFixed(0)}%';
            if(received / total ==1){
              btnTitle = '安装新版本';
            }
          });
        }
      }
    });
  }
}
